package com.hevery.web.filter;

import com.hevery.warpper.HttpServletResponseCopier;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Hevery
 * @Description: 获得请求流中的ResponseBody中的内容
 * @Date: Created on 2017/10/8
 * @Modified By:
 */
//@Component
public class ResponseFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("response filter init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        /**在doFilter将ServletResponse进行写回之前，先将响应流ServletResponse包装成HttpServletResponseCopier*/
        HttpServletResponseCopier responseCopier = new HttpServletResponseCopier((HttpServletResponse) response);

        /**doFilter将包装后的HttpServletResponseCopier当做ServletResponse，进行写回*/
        filterChain.doFilter(request,responseCopier);

        /**写完之后就会获得关于ServletResponse的一份拷贝*/
        byte[] copier = responseCopier.getCopy();

        System.out.println("ResponseBody :" +new String(copier,responseCopier.getCharacterEncoding()));
        responseCopier.flushBuffer();
    }

    @Override
    public void destroy() {
        System.out.println("response filter destroy");
    }
}
